package com.walkthecow.justdraw;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;

import com.walkthecow.justdraw.ShakeEventListener.OnShakeListener;

public class JustDraw extends Activity implements OnShakeListener{

	private JustDrawView justDrawView;
	private String mFileName;
	private String mSavePath = "JustDraw";
	private SensorManager mSensorManager;
	private ShakeEventListener mSensorListener;
	private boolean mShakeToClear = false; 

	private int[] colourValuesPen = new int[4];
	private int[] colourValuesBackground = new int[4];
	

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		//Set the default preferences if no user preferences have been set.
		PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
		
		//Create the layout
		setContentView(R.layout.just_draw_layout);
		
		//Get references to the main view
		justDrawView = (JustDrawView)findViewById(R.id.justdrawview);
		
		//Create Shake Listener
		mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
		mSensorListener = new ShakeEventListener();
		mSensorListener.setOnShakeListener(this);
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		//Create the menu.
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.menu.just_draw_menu, menu);

		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item){

		Intent i;
		
		switch(item.getItemId()){
		case R.id.menu_redo:
			//Undo
			justDrawView.onClickRedo();
			return true;
		case R.id.menu_save:
			//Save the picture
			savePicture();
			return true;
		case R.id.menu_about:
			//Show the About activity
			startActivity(new Intent(this, About.class));
			return true;
		case R.id.menu_settings:
			//Show Preferences
			i = new Intent(this,Preferences.class);
			startActivityForResult(i, Constants.ACTIVITY_SETTINGS);
			return true;
		case R.id.menu_open:
			i = new Intent(Intent.ACTION_GET_CONTENT);
			i.setType("image/*");
			startActivityForResult(i, Constants.ACTIVITY_SELECT_PICTURE);
			return true;
		case R.id.menu_pen_advanced:
			i = new Intent(this, PenSettingsAdvanced.class);
			i.putExtras(setBundlePenAdvanced());
			startActivityForResult(i, Constants.ACTIVITY_PEN_SETTINGS_ADVANCED);
			break;
		case R.id.menu_share:
			Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
			emailIntent.setType("image/jpeg");
			emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject");
			emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Body");
			startActivity(emailIntent);
			break;
		}
		return super.onOptionsItemSelected(item);	
	}

	public void buttonClick(View view){

		Intent intent = null;

		switch(view.getId()){
		case R.id.button_erase:
			justDrawView.setLineColour(justDrawView.getBackgroundColour());
			break;
		case R.id.button_pen:
			intent = new Intent(this, PenSettings.class);
			intent.putExtra(Constants.KEY_EFFECT, justDrawView.getEffect());
			intent.putExtra(Constants.KEY_WIDTH, justDrawView.getLineWidth());
			intent.putExtra(Constants.KEY_SHADOW, justDrawView.isShadow());
			startActivityForResult(intent, Constants.ACTIVITY_PEN_SETTINGS);
			break;
		case R.id.button_new:
			intent	 = new Intent(this, ColourPicker.class);
			intent.putExtra(ColourPicker.KEY_TITLE, getText(R.string.title_screen_background_colour));
			intent.putExtra(ColourPicker.KEY_COLOUR, justDrawView.getBackgroundColour());
			startActivityForResult(intent, Constants.ACTIVITY_BACKGROUND_COLOUR);
			break;
		case R.id.button_undo:
			justDrawView.onClickUndo();
			break;
		case R.id.button_colour:
			intent	 = new Intent(this, ColourPicker.class);
			intent.putExtra(ColourPicker.KEY_TITLE,getText(R.string.title_screen_pen_colour));
			intent.putExtra(ColourPicker.KEY_COLOUR, justDrawView.getLineColour());
			startActivityForResult(intent, Constants.ACTIVITY_LINE_COLOUR);
			break;
		}
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
		super.onActivityResult(requestCode, resultCode, intent);

		if(resultCode == RESULT_OK){
			switch(requestCode) { 
			case Constants.ACTIVITY_PEN_SETTINGS:
				int width = intent.getIntExtra(Constants.KEY_WIDTH, justDrawView.getLineWidth());
				int effect = intent.getIntExtra(Constants.KEY_EFFECT, justDrawView.getEffect());
				boolean shadow = intent.getBooleanExtra(Constants.KEY_SHADOW, justDrawView.isShadow());
				justDrawView.setLineWidth(width);
				justDrawView.setEffect(effect);
				justDrawView.setShadow(shadow);
				break;
			case Constants.ACTIVITY_PEN_SETTINGS_ADVANCED:
				getBundlePenAdvanced(intent.getExtras());
				break;
			case Constants.ACTIVITY_SELECT_PICTURE:
				getPicture(intent);
				break;
			case Constants.ACTIVITY_BACKGROUND_COLOUR:
				colourValuesBackground = intent.getIntArrayExtra(ColourPicker.KEY_COLOUR);
				justDrawView.setBackgroundColour(colourValuesBackground);
				justDrawView.onClickNew(null);
				break;
			case Constants.ACTIVITY_LINE_COLOUR:
				colourValuesPen = intent.getIntArrayExtra(ColourPicker.KEY_COLOUR);
				justDrawView.setLineColour(colourValuesPen);
				break;
			case Constants.ACTIVITY_SETTINGS:
				getPrefs();
				break;
			}
		}
	}

	private void getPicture(Intent intent){
		Uri selectedImageUri = intent.getData();
		//FILE Manager
		String filemanagerPath = selectedImageUri.getPath();
		//MEDIA GALLERY
		String selectedImagePath = getPath(selectedImageUri);

		Bitmap selectedImage = null;

		//NOW WE HAVE OUR WANTED STRING
		if(selectedImagePath!=null){
			selectedImage = BitmapFactory.decodeFile(selectedImagePath);
		}else{
			selectedImage = BitmapFactory.decodeFile(filemanagerPath);
		}

		if(selectedImage!=null){
			//Resize the image to fit the view
			Bitmap resizedImage = Bitmap.createScaledBitmap(selectedImage, justDrawView.getWidth(), justDrawView.getHeight(), true);
			justDrawView.onClickNew(resizedImage);
		}
	}

	public String getPath(Uri uri) {
		String[] projection = { MediaStore.Images.Media.DATA };
		Cursor cursor = getContentResolver().query(uri, projection, null, null, null);

		if(cursor!=null)
		{
			//HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
			//THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
			int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
			cursor.moveToFirst();
			return cursor.getString(column_index);
		}
		else return null;
	}

	private void getPrefs(){
		
		SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
		mSavePath = sharedPref.getString(getText(R.string.preference_save_path).toString(), "JustDraw");
		mShakeToClear = sharedPref.getBoolean(getText(R.string.preference_shake_to_clear).toString(), false);
		mFileName = sharedPref.getString(getText(R.string.preference_file_name).toString(), "JustDraw");
		boolean preference_full_screen = sharedPref.getBoolean(getText(R.string.preference_full_screen).toString(), false);

		updateFullscreenStatus(preference_full_screen);
		
	}

	private void savePicture(){
		if (justDrawView != null){
			
			SaveBitmap saveBitmap = new SaveBitmap(this, justDrawView, mFileName + System.currentTimeMillis(), mSavePath);
			saveBitmap.saveView();
		}
	}

	private void createNotification(){

		//Creating notification as a test.  Wouldn't normally do this.
		String ns = Context.NOTIFICATION_SERVICE;
		NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);

		int icon = R.drawable.ic_launcher;
		CharSequence tickerText = "Hello";
		long when = System.currentTimeMillis();

		Notification notification = new Notification(icon, tickerText, when);

		Context context = getApplicationContext();
		CharSequence contentTitle = "My notification";
		CharSequence contentText = "Hello World!";
		Intent notificationIntent = new Intent(this, this.getClass());
		PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

		notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);

		//private static final int HELLO_ID = 1;
		//mNotificationManager.notify(HELLO_ID, notification);
		mNotificationManager.notify(1, notification);

		//******************************************************
	}
	@Override
	protected void onResume() {
		super.onResume();
		
		getPrefs();
		
		mSensorManager.registerListener(mSensorListener,
				mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
				SensorManager.SENSOR_DELAY_UI);
	}

	@Override
	protected void onPause() {
		mSensorManager.unregisterListener(mSensorListener);
		super.onStop();
	}	

	private void updateFullscreenStatus(boolean bUseFullscreen)
	{   
		if(bUseFullscreen)
		{
			getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
			getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
		}
		else
		{
			getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
			getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
		}

	}

	@Override
	public void onShake() {
		if (mShakeToClear){
			//TODO Remove Toast
			Toast.makeText(JustDraw.this, getText(R.string.text_shake), Toast.LENGTH_SHORT).show();
			justDrawView.onClickNew(null);	
		}
	}
	
	private Bundle setBundlePenAdvanced(){
		Bundle extras = new Bundle();
		extras.putInt(Constants.KEY_EFFECT, justDrawView.getEffect());
		extras.putInt(Constants.KEY_BLURSTYLE, justDrawView.getBlurStyle());
		extras.putInt(Constants.KEY_CAP, justDrawView.getStrokeCap());
		extras.putInt(Constants.KEY_JOIN, justDrawView.getStrokeJoin());
		extras.putInt(Constants.KEY_STYLE, justDrawView.getStyle());

		extras.putFloat(Constants.KEY_SHADOWDX, justDrawView.getShadowDX());
		extras.putFloat(Constants.KEY_SHADOWDY, justDrawView.getShadowDY());
		extras.putFloat(Constants.KEY_SHADOWRADIUS, justDrawView.getShadowRadius());
		extras.putFloat(Constants.KEY_BLURRADIUS, justDrawView.getBlurRadius());
		extras.putFloatArray(Constants.KEY_EMBOSSDIRECTION, justDrawView.getEmbossDirection());
		extras.putFloat(Constants.KEY_EMBOSSAMBIENT, justDrawView.getEmbossAmbient());
		extras.putFloat(Constants.KEY_EMBOSSRADIUS, justDrawView.getEmbossRadius());
		extras.putFloat(Constants.KEY_EMBOSSSPECULAR, justDrawView.getEmbossSpecular());
		return extras; 
	}
	
	private void getBundlePenAdvanced(Bundle extras){
		justDrawView.setEffect(extras.getInt(Constants.KEY_EFFECT));
		justDrawView.setBlurStyle(extras.getInt(Constants.KEY_BLURSTYLE));
		justDrawView.setStrokeCap(extras.getInt(Constants.KEY_CAP));
		justDrawView.setStrokeJoin(extras.getInt(Constants.KEY_JOIN));
		justDrawView.setStyle(extras.getInt(Constants.KEY_STYLE));

		justDrawView.setShadowDX(extras.getFloat(Constants.KEY_SHADOWDX));
		justDrawView.setShadowDY(extras.getFloat(Constants.KEY_SHADOWDY));
		justDrawView.setShadowRadius(extras.getFloat(Constants.KEY_SHADOWRADIUS));
		justDrawView.setBlurRadius(extras.getFloat(Constants.KEY_BLURRADIUS));
		justDrawView.setEmbossDirection(extras.getFloatArray(Constants.KEY_EMBOSSDIRECTION));
		justDrawView.setEmbossAmbient(extras.getFloat(Constants.KEY_EMBOSSAMBIENT));
		justDrawView.setEmbossRadius(extras.getFloat(Constants.KEY_EMBOSSRADIUS));
		justDrawView.setEmbossSpecular(extras.getFloat(Constants.KEY_EMBOSSSPECULAR));
	}
}
